package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.EnrollStagePeriod;
import com.xmy.cultivate.entity.EnrollStageTime;
import com.xmy.cultivate.entity.EnrollStageType;
import com.xmy.cultivate.service.IEnrollStagePeriodService;
import com.xmy.cultivate.service.IEnrollStageTimeService;
import com.xmy.cultivate.service.IEnrollStageTypeService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <阶段时间>
 * 阶段时间表 前端控制器
 * </阶段时间>
 *
 * @author hpiggy
 * @since 2024-09-04
 */
@RestController
@RequestMapping("/api/enrollStageTime")
public class EnrollStageTimeController {
    @Autowired
    IEnrollStageTimeService iEnrollStageTimeService;

    @Autowired
    IEnrollStageTypeService iEnrollStageTypeService;

    @Autowired
    IEnrollStagePeriodService iEnrollStagePeriodService;


    @GetMapping()
    public Result getEnrollStagePeriod(@RequestParam Map<String, String> reMap) {
        Integer pageNum = StringUtils.isEmpty(reMap.get("pageNum")) ? 1 : Integer.valueOf(reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty(reMap.get("pageSize")) ? 10 : Integer.valueOf(reMap.get("pageSize"));
        IPage<EnrollStageTime> iPage = new Page<>(pageNum, pageSize);

        String yearPart = reMap.get("yearPart");
        String quarterNum = reMap.get("quarterNum");
        String stageTypeId = reMap.get("stageTypeId");

        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        wrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        wrapper.eq(StringUtils.isNotBlank(stageTypeId), "stage_type_id", stageTypeId);

        iEnrollStageTimeService.page(iPage, wrapper);

        for (EnrollStageTime stageTime : iPage.getRecords()) {
            List<EnrollStagePeriod> enrollStagePeriodList = iEnrollStagePeriodService.list(new QueryWrapper<EnrollStagePeriod>().eq("stage_time_id", stageTime.getId()));
            if (Objects.nonNull(enrollStagePeriodList)) {
                stageTime.setEnrollStagePeriodList(enrollStagePeriodList);
            }
            EnrollStageType enrollStageName = iEnrollStageTypeService.getById(stageTime.getStageTypeId());
            if (Objects.nonNull(enrollStageName)) {
                stageTime.setEnrollStageName(enrollStageName.getName());
                stageTime.setType(enrollStageName.getType());
            }
            stageTime.setQuarterName(CommonUtil.getQuarterNameForId(stageTime.getQuarterNum()));
        }

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()), Code.GET_OK_MSG);
    }



    @PostMapping("")
    @ApiOperation("添加阶段时间")
    public Result saveEnrollStagePeriod(@RequestBody EnrollStageTime enrollStageTime) {
        if (enrollStageTime.getType() == 1 && Objects.nonNull(enrollStageTime.getEnrollStagePeriodList())) {
            // 检查是否有冲突
            if (CommonUtil.hasDateConflict(enrollStageTime.getEnrollStagePeriodList())) {
                return new Result(Code.ERROR, null, "提示：周期时间段冲突，请调整后重试");
            }
        }

        // 判断是否重复添加
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("stage_type_id", enrollStageTime.getStageTypeId());
        wrapper.eq("year_part", enrollStageTime.getYearPart());
        wrapper.eq("quarter_num", enrollStageTime.getQuarterNum());
        Long count = iEnrollStageTimeService.count(wrapper);

        String name = iEnrollStageTypeService.getById(enrollStageTime.getStageTypeId()).getName();
        if (count > 0L) {
            String reminder = "提示：【" + enrollStageTime.getYearPart() + CommonUtil.getQuarterNameForId(enrollStageTime.getQuarterNum()) + name + "】该阶段时间已存在，请勿重复添加";
            return new Result(Code.ERROR, null, reminder);
        }

        // 判断日期是否冲突
//        Integer countByDate = iEnrollStageTimeService.countByDate(enrollStageTime.getStartDate(), enrollStageTime.getEndDate());
//        if (countByDate > 0) {
//            String reminder = "提示：【" + enrollStageTime.getStartDate() + "~" + enrollStageTime.getEndDate() + "】该日期段已存在，请勿重复添加";
//            return new Result(Code.ERROR, null, reminder);
//        }

        iEnrollStageTimeService.save(enrollStageTime);

        if (enrollStageTime.getType() == 1 && Objects.nonNull(enrollStageTime.getEnrollStagePeriodList())) {
            for (EnrollStagePeriod period : enrollStageTime.getEnrollStagePeriodList()) {
                period.setStageTimeId(enrollStageTime.getId());
                iEnrollStagePeriodService.save(period);
            }
        }

        return new Result(Code.OK, null, Code.OK_MSG);
    }

    @PutMapping("")
    @ApiOperation("修改阶段时间")
    public Result updateEnrollStagePeriod(@RequestBody EnrollStageTime enrollStageTime) {
        if (enrollStageTime.getType() == 1 && Objects.nonNull(enrollStageTime.getEnrollStagePeriodList())) {
            // 检查是否有冲突
            if (CommonUtil.hasDateConflict(enrollStageTime.getEnrollStagePeriodList())) {
                return new Result(Code.ERROR, null, "提示：周期时间段冲突，请调整后重试");
            }
        }

        EnrollStageTime stageTime = iEnrollStageTimeService.getById(enrollStageTime.getId());

        if (Objects.isNull(stageTime)) {
            return new Result(Code.OK, null, "该阶段时间不存在");
        }

        // 判断是否重复添加
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("stage_type_id", enrollStageTime.getStageTypeId());
        wrapper.eq("year_part", enrollStageTime.getYearPart());
        wrapper.eq("quarter_num", enrollStageTime.getQuarterNum());
        wrapper.ne("id", enrollStageTime.getId());
        Long count = iEnrollStageTimeService.count(wrapper);

        if (count > 1L) {
            String name = iEnrollStageTypeService.getById(enrollStageTime.getStageTypeId()).getName();
            String reminder = "提示：【" + enrollStageTime.getYearPart() + CommonUtil.getQuarterNameForId(enrollStageTime.getQuarterNum()) + name + "】该阶段时间已存在，请勿重复添加";
            return new Result(Code.ERROR, null, reminder);
        }

        // 判断日期是否冲突
//        Integer countByDate = iEnrollStageTimeService.countByDate(enrollStageTime.getStartDate(), enrollStageTime.getEndDate());
//        if (countByDate > 1) {
//            String reminder = "提示：【" + enrollStageTime.getStartDate() + "至" + enrollStageTime.getEndDate() + "】该日期段已存在，请勿重复添加";
//            return new Result(Code.ERROR, null, reminder);
//        }

        if (enrollStageTime.getType() == 1 && Objects.nonNull(enrollStageTime.getEnrollStagePeriodList())) {
            iEnrollStagePeriodService.remove(new QueryWrapper<EnrollStagePeriod>().eq("stage_time_id", enrollStageTime.getId()));
            for (EnrollStagePeriod period : enrollStageTime.getEnrollStagePeriodList()) {
                period.setStageTimeId(enrollStageTime.getId());
                iEnrollStagePeriodService.save(period);
            }
        }

        iEnrollStageTimeService.updateById(enrollStageTime);

        return new Result(Code.OK, null, Code.OK_MSG);
    }

    @DeleteMapping("")
    @ApiOperation("删除阶段时间")
    public Result deleteEnrollStageTime(@RequestParam(value = "id") String id) {
        EnrollStageTime stageTime = iEnrollStageTimeService.getById(id);

        if (Objects.isNull(stageTime)) {
            return new Result(Code.ERROR, null, "该阶段时间不存在");
        }

        iEnrollStagePeriodService.remove(new QueryWrapper<EnrollStagePeriod>().eq("stage_time_id", stageTime.getId()));
        iEnrollStageTimeService.removeById(id);

        return new Result(Code.DELETE_OK, null, Code.DELETE_OK_MSG);
    }

    @PostMapping("/batchRemove")
    @ApiOperation("批量删除阶段时间")
    public Result deleteEnrollStageTime(@RequestBody Map<String, Object> reMap) {
        List<String> idList = (List<String>) reMap.get("idList");

        for (String id : idList) {
            EnrollStageTime stageTime = iEnrollStageTimeService.getById(id);
            if (Objects.isNull(stageTime)) {
                return new Result(Code.ERROR, null, "该阶段时间不存在");
            }
            iEnrollStagePeriodService.remove(new QueryWrapper<EnrollStagePeriod>().eq("stage_time_id", stageTime.getId()));
            iEnrollStageTimeService.removeById(id);
        }

        return new Result(Code.DELETE_OK, null, Code.DELETE_OK_MSG);
    }


}
